package com.changgou.seckill.task;

import com.changgou.entity.DateUtil;
import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author 戴金华
 * @date 2019-12-29 8:26
 */
@Component
public class PushGoodsToRedis {

    public static final String SECKILL_GOODS_KEY = "seckill_goods_";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    /**
     * 每一分钟执行一次 将数据库中符合条件的商品放入缓存中
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void pushGoodsToRedis(){

        System.out.println("开始录入商品");
        //获取时间段集合
        List<Date> dateMenus = DateUtil.getDateMenus();

        for (Date dateMenu : dateMenus) {

            String dateTime = DateUtil.date2Str(dateMenu);

            //设置查询条件
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status","1");  //审核状态 =1
            criteria.andGreaterThan("stockCount",0);//剩余库存数量 >0
            criteria.andGreaterThanOrEqualTo("startTime",DateUtil.dateToStrPattern(dateMenu));//开始时间>dateTime
            criteria.andLessThanOrEqualTo("endTime",DateUtil.dateToStrPattern(DateUtil.addDateHour(dateMenu,2)));//结束时间<dateTime+2

            //确保当前缓存中不存在该商品
            Set ids = redisTemplate.boundHashOps(SECKILL_GOODS_KEY + dateTime).keys();
            if (ids!=null&&ids.size()>0){
                criteria.andNotIn("id",ids);
            }

            //查询数据库中数据放入缓存中
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            for (SeckillGoods seckillGood : seckillGoods) {
                //存入到redis中
                redisTemplate.boundHashOps(SECKILL_GOODS_KEY+dateTime).put(seckillGood.getId(),seckillGood);
                //给每隔商品做个队列
                redisTemplate.boundListOps("SeckillGoodsQueue_"+seckillGood.getId()).leftPush(putAllIds(seckillGood.getStockCount(),seckillGood.getId()));
            }

        }
    }


    /**
     * 获取每隔商品的id集合
     * @param num
     * @param id
     * @return
     */
    public Long[] putAllIds(Integer num,Long id){
        Long[] ids = new Long[num];
        for (int i = 0; i < num; i++) {
            ids[i] = id;
        }
        return ids;
    }
}
